package com.demo.apparel.controller.web;

import com.demo.apparel.common.Result;
import com.demo.apparel.dto.web.AgreementPageQueryDTO;
import com.demo.apparel.entity.Agreement;
import com.demo.apparel.service.web.WebAgreementService;
import com.demo.apparel.utils.JwtUtils;
import com.demo.apparel.vo.PageVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/web/agreement")
@Tag(name = "同意协议接口", description = "同意协议信息")
public class WebAgreementController {

    @Autowired
    private WebAgreementService webAgreementService;

    @Autowired
    private JwtUtils jwtUtils;

//    @PostMapping("/create")
//    public Result<Agreement> createAgreement(@RequestBody Agreement agreement) {
//        Agreement isSaved = webAgreementService.saveAgreement(agreement);
//        return Result.success(isSaved);
//    }
    /**
     * 创建协议
     * @param agreement 协议数据
     * @param request HTTP 请求对象
     * @return 创建的协议
     */
    @PostMapping("/create")
    @Operation(summary = "创建协议")
    public Result<Agreement> createAgreement(@RequestBody Agreement agreement, HttpServletRequest request) {
        // 从请求的 Authorization header 中获取 token
        String token = request.getHeader("Authorization");

        if (token == null || !token.startsWith("Bearer ")) {
            return (Result<Agreement>) Result.failure("Token 无效");
        }

        // 提取 token 中的用户 ID
        String userId = jwtUtils.getUserId(token.substring(7));  // 去掉 "Bearer " 前缀

        // 设置协议的 adminId 为当前用户的 userId
        agreement.setAdminId(userId);

        // 保存协议
        Agreement isSaved = webAgreementService.saveAgreement(agreement);
        return Result.success(isSaved);
    }

    @GetMapping("/list")
    public Result<List<Agreement>> getAllAgreements() {
        List<Agreement> agreements = webAgreementService.getAllAgreements();
        return Result.success(agreements);
    }


    @GetMapping("/{id}")
    public Result<Agreement> getAgreementById(@PathVariable String id) {
        Agreement agreement = webAgreementService.getAgreementById(id);
        return Result.success(agreement);
    }

    @PostMapping("/page")
    @Operation(summary = "分页查询协议（可按isActive、version、创建时间、管理员昵称查询）")
    public Result<PageVO<Agreement>> pageAgreements(@RequestBody AgreementPageQueryDTO dto) {
        return Result.success(webAgreementService.pageQueryAgreements(dto));
    }
}
